package com.liuchuan.template.service.serviceImpl;

import com.liuchuan.template.dao.PeopleDAO;
import com.liuchuan.template.domain.entity.People;
import com.liuchuan.template.domain.vo.PeopleVO;
import com.liuchuan.template.service.PeopleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class PeopleServiceImpl implements PeopleService {

    @Autowired
    private PeopleDAO peopleDAO;

    @Override
    public PeopleVO getById(Long id) {
        Optional<People> byId = peopleDAO.findById(id);
        if (byId.isEmpty()) {
            log.info("无此记录");
            return null;
        }

        PeopleVO peopleVO = new PeopleVO();
        BeanUtils.copyProperties(byId.get(), peopleVO);
        return peopleVO;
    }

    @Override
    public PeopleVO add(People people) {
        if (people.getName() == null || people.getPhoneNumber() == null) {
            log.info("名字电话不能为空");
            return null;
        }
        People a = peopleDAO.save(people);

        PeopleVO peopleVO = new PeopleVO();
        BeanUtils.copyProperties(a, peopleVO);
        return peopleVO;
    }

    @Override
    public PeopleVO update(People people) {
        if (people.getId() == null) {
            log.info("id不能为空");
            return null;
        }
        if (people.getAddress() == null && people.getPhoneNumber() == null && people.getSex() == null && people.getName() == null) {
            log.info("修改信息不能为空");
            return null;
        }
        Optional<People> byId = peopleDAO.findById(people.getId());
        if (byId.isEmpty()){
            log.info("无此记录");
            return null;
        }
        People people1 = byId.get();
        BeanUtils.copyProperties(people,people1);

        People save = peopleDAO.save(people1);


        PeopleVO peopleVO = new PeopleVO();
        BeanUtils.copyProperties(save, peopleVO);
        return peopleVO;
    }

    @Override
    public PeopleVO deleteById(Long id) {
        Optional<People> byId = peopleDAO.findById(id);
        if (byId.isEmpty()){
            log.info("无此记录");
            return null;
        }
        peopleDAO.deleteById(id);

        PeopleVO peopleVO = new PeopleVO();
        BeanUtils.copyProperties(byId.get(), peopleVO);
        return peopleVO;
    }


}
